package com.joseph.websocket.client;

import com.alibaba.fastjson.serializer.StringCodec;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.TimeUnit;

public class NodeClient {

    private static Channel channel;

    private StringEncoder stringEncoder = new StringEncoder();

    private StringDecoder stringDecoder = new StringDecoder();

    public static Channel getChannel() {
        return channel;
    }

    public NodeClient () {
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap boot = new Bootstrap();
        boot.option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true)
                //.option(ChannelOption.SO_BACKLOG, 1024 * 1024 * 10)
                .group(group)
                //.handler(new LoggingHandler(LogLevel.INFO))
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline p = socketChannel.pipeline();
                        p.addLast(stringEncoder, stringDecoder);
                        p.addLast(new IdleStateHandler(0, 0 ,10));
                        p.addLast("nodeClientHandler", new NodeClientHandler());
                    }
                });
        ChannelFuture cf = null;
        try {
            cf = boot.connect("localhost",8090).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if ((cf != null) && cf.isSuccess()) {
            if (channel != null) {
                channel.close();
            }
            channel = cf.channel();
        }
    }

}